var BG_LAYER = 1000;
var CARD_LAYER = 1001;
var TANK_LAYER = 1002;
var UI_LAYER = 1003;

var GameScn = cc.Scene.extend({
	onEnter:function(){
		this._super();
		
		var bg = new BgLayer();
		bg.init();
		this.addChild(bg, 0, BG_LAYER);
		this.bgLayer = bg;
		
		var card = new CardLayer();
		card.init();
		this.addChild(card, 1, CARD_LAYER);
		this.cardLayer = card;
		
		var tank = new TankLayer();
		tank.init();
		this.addChild(tank, 2, TANK_LAYER);
		this.tankLayer = tank;
		
		var ui = new UILayer();
		ui.init();
		this.addChild(ui, 3, UI_LAYER);
		this.uiLayer = ui;

		TW.gameScn = this;
		this.schedule(this.checkSync,1);
		
		createRoom(TW.room_h, TW.room_w);
		for(var id in TW.players){
			createTank(TW.players[id]);
		}
	},
	
	onExit:function(){
		TW.gameScn = null;
	},
	
	checkSync:function(){
		if(!TW.svrWait){
			return;
		}
		
		if(TW.evts_card.length==0 && TW.evts_tank.length==0 && TW.waitAction==0){
			TW.svrWait = false;
			TW.sock.emit('sync');
			
			if(TW.win){
				showWinnerDlg(TW.win);
			}
		}
	}
});

var MAP_OFFSET = cc.p(35,0);
var TAG_BATCH = 1;
var BgLayer = cc.Layer.extend({
	init:function(){
		this._super();		
			
		var bg = cc.Sprite.create(R_ROOM_BIGBG);
		var sz = cc.Director.getInstance().getWinSize();
		bg.setAnchorPoint(cc.PointZero());
		this.addChild(bg, 1);
		
		var batch = cc.SpriteBatchNode.create(R_ROOM_GRIDBG, TW.room_h*TW.room_w);
		this.addChild(batch, 2, TAG_BATCH);
		batch.setPosition(MAP_OFFSET);
		this.batch = batch;
	}
});

var TAG_CARD_BATCH = 1;
var CardLayer = cc.Layer.extend({
	init:function(){
		this._super();
		
		var batch = cc.SpriteBatchNode.create(R_ALL_CARD, TW.room_h*TW.room_w);
		this.addChild(batch, 0, TAG_CARD_BATCH);
		var offset = cc.p(MAP_OFFSET.x+GRID_SIZE/2,MAP_OFFSET.y+GRID_SIZE/2);
		batch.setPosition(offset);
		this.batch = batch;
		
		this.schedule(this.renderCardEvent, 1);
	},
	
	renderCardEvent:function(){
		TW.evts_card = TW.evts_card || [];
		var row = TW.evts_card[0];		
		if(row){
			TW.evts_card.shift();
			addCardRow(row);
		}
	}
});

var TAG_TANK_PARENT = 1;
var TAG_EFFECT_PARENT = 2;
var TankLayer = cc.Layer.extend({
	init:function(){
		this._super();
		
		var offset = cc.p(MAP_OFFSET.x+GRID_SIZE/2,MAP_OFFSET.y+GRID_SIZE/2);
		var parent = cc.Layer.create();
		this.addChild(parent, 0, TAG_TANK_PARENT);
		parent.setPosition(offset);
		this.tank = parent;
		
		var effect = cc.Layer.create();
		this.addChild(effect, 1, TAG_EFFECT_PARENT);
		effect.setPosition(offset);
		this.effect = effect;

		this.schedule(this.renderTankEvent, 1);
	},

	handleMove: function (evt) {
	    var tank = TW.tanks[evt.id];
	    if (tank) {
	        var r = addWaiting(1);
	        moveTank(evt.id, evt.pos.x, evt.pos.y);
	        addTankAction(tank, cc.CallFunc.create(function () {
				var card = TW.grids[evt.pos.y][evt.pos.x];
				TW.grids[evt.pos.y][evt.pos.x] = null;
				if(card){
					card.removeFromParent(true);
				}
	            r.r();
	        }));
	        getTankRunAction(tank)();
			
			tank.dbuff = tank.dbuff || {};
			for(var t in tank.dbuff){
				if(tank.dbuff[t]>0){
					tank.dbuff[t] -= 1;
					updateBuffBoard(tank.player.name, t, tank.dbuff[t]);
				}
			}
	    }
	},

	handleConflictFailed:function(evt){
	    var tank = TW.tanks[evt.b];
	    if(tank){
	        var r = addWaiting(1);
	        if(evt.pos){
	            addTankAction(tank, cc.TargetedAction.create(tank.shade,cc.MoveTo.create(0.1, grid2pos(evt.pos.x, evt.pos.y))));
	            tank.player.pos = evt.pos;
	        }					
	        addTankAction(tank, cc.CallFunc.create(function(t,data){
	            chgHP(data.b, data.hp);
	            r.r();
	        },tank,evt));
	        getTankRunAction(tank)();
	    }
	},

	handleHit: function (evt) {
	    if (evt.b) {
	        var ta = TW.tanks[evt.a];
	        var tb = TW.tanks[evt.b];
	        if (ta && tb) {
	            var r = addWaiting(1);
				if(evt.t==BULLET){
					tankBullet(evt.a, tb.player.pos.x, tb.player.pos.y);
				}
				else{
					tankShoot(evt.a, tb.player.pos.x, tb.player.pos.y);
				}
	            addTankAction(ta, cc.CallFunc.create(function (tank, evt) {
	                chgHP(evt.b, evt.hp);
	                r.r();
	            }, ta, evt));
	            getTankRunAction(ta)();
	        }
	    }
	    else {
	        var tank = TW.tanks[evt.a];
	        if (tank) {
	            var r = addWaiting(1);
	            if (evt.hp < tank.player.hp) {
	                createExplose(tank.player.pos.x, tank.player.pos.y);
	            }
	            else {
	                createHealth(tank.player.pos.x, tank.player.pos.y);
	            }
	            chgHP(evt.a, evt.hp);
	            this.scheduleOnce(function () {
	                r.r();
	            }, 1);
	        }
	    }
	},

	handleGBuffAction: function (evt) {
	    if (evt.b) {
	        var ta = TW.tanks[evt.a];
	        var tb = TW.tanks[evt.b];
	        if (tb) {
	            tb.dbuff = tb.dbuff || {};
	            tb.dbuff[evt.t] = tb.dbuff[evt.t] || evt.cnt;
				updateBuffBoard(tb.player.name, evt.t, evt.cnt);
	        }

	        if (ta && tb && evt.cnt > 0) {
	            var r = addWaiting(1);
				tankShoot(evt.a, tb.player.pos.x, tb.player.pos.y,true);				
	            addTankAction(ta, cc.CallFunc.create(function (tank, evt) {
	                if (evt.t == ONFIRE) {
	                    createFire(evt.b);
	                }
	                else if (evt.t == FREEZE) {
	                    createSleep(evt.b);
	                }
	                r.r();
	            }, ta, evt));
	            getTankRunAction(ta)();
	        }
	        return tb;
	    }
	    else{
	        var r = addWaiting(1);
	        var tank = TW.tanks[evt.a];
	        if (tank) {
	            tank.dbuff = tank.dbuff || {};
	            tank.dbuff[evt.t] = tank.dbuff[evt.t] || 0;
				updateBuffBoard(tank.player.name, evt.t, evt.cnt);
	        }
	        if (tank && evt.cnt > 0) {
	            pickItem(tank.player.pos.x, tank.player.pos.y, evt.t, null, evt.cnt - tank.dbuff[evt.t]);
	        }
	        this.scheduleOnce(function () {
	            r.r();
	        }, 1);
	        return tank;
	    }
	},

	handleGBuffEffect: function (target, evt) {
	    if (evt.t == SHELL) {
	        if (evt.cnt > 0) {
	            createShell(target.player.id);
	        }
	        else {
	            target.shell.removeFromParent(true);
	            delete target.shell;
	        }
	    }
	    else if (evt.t == HIDE) {
	        if (evt.cnt > 0) {
	            target.hat.runAction(cc.FadeOut.create(0.5));
	            target.body.runAction(cc.FadeOut.create(0.7));
	            target.root.runAction(cc.FadeOut.create(1));
	        }
	        else {
	            target.hat.runAction(cc.FadeIn.create(1));
	            target.body.runAction(cc.FadeIn.create(0.7));
	            target.root.runAction(cc.FadeIn.create(0.5));
	        }
	    }
	    else if (evt.t == ONFIRE) {
	        if (evt.cnt == 0) {
	            target.fire.removeFromParent(true);
	            delete target.fire;
	        }
	    }
	    else if (evt.t == FREEZE) {
	        if (evt.cnt == 0) {
	            target.sleep.removeFromParent(true);
	            delete target.sleep;
	        }
	    }
	},
	
	handleShootBox: function(evt){
		if(evt.b){
			chgHP(evt.b, evt.hp);
		}
		else{
			var r = addWaiting(1,2);
			fireAround(evt.a)();	
		}
	},
	
	handleShootLn:function(evt){
		if(evt.b){
			chgHP(evt.b, evt.hp);
		}
		else{
			addWaiting(1, 2);
			createLaser(evt.a, evt.x, evt.y)();
		}
	},
	
	renderTankEvent:function(){
		TW.waitAction = TW.waitAction || 0;
		if(TW.waitAction>0){
			return;
		}
		
		var maxevt = 10;
		TW.evts_tank = TW.evts_tank || [];
		var firstEvt = TW.evts_tank[0] && TW.evts_tank[0].cmd;
		while(TW.evts_tank.length>0 && maxevt>0){
			maxevt -= 1;
			var evt = TW.evts_tank[0];
			TW.curEvt = evt;
			if(evt.cmd!=firstEvt){
				break;
			}
			TW.evts_tank.shift();

			if (evt.cmd == 'pos') {
			    this.handleMove(evt);
			}
			else if(evt.cmd=='conflict'){
				createConflict(evt.pos.x, evt.pos.y, evt.id);
				var r = addWaiting(1);
				this.scheduleOnce(function(){
					r.r();
				}, 1);
			}
			else if(evt.cmd=='conflictfail'){				
			    this.handleConflictFailed(evt);
			}
			else if(evt.cmd=='shootbox' || evt.cmd=='sbhit'){	
				this.handleShootBox(evt);
			}
			else if(evt.cmd=='shootln' || evt.cmd=='slhit'){
				if(evt.cmd=='shootln'){
					firstEvt = null;
				}
				this.handleShootLn(evt);
			}
			else if(evt.cmd=='ghit'){
				firstEvt = null;
				this.handleHit(evt);
			}
			else if(evt.cmd=='gbuff'){
				firstEvt = null;		
				var target = this.handleGBuffAction(evt);
				if (target) {
				    this.handleGBuffEffect(target, evt);
				}
			}
			else if(evt.cmd=='clear'){			
				var tank = TW.tanks[evt.a];
				if(tank){
					var r = addWaiting(1);
					addTankAction(tank, cc.RotateBy.create(1,360*3));
					addTankAction(tank, cc.CallFunc.create(function(){
						r.r();
					}));
					getTankRunAction(tank)();
				}
			}
			else if(evt.cmd=='pick'){
				Tool.createTip(TW.gameScn.uiLayer, g_cardList[evt.t], 
					{color:cc.c3b(102, 0, 204), size:40, time:1.5});
			}
		}
	}
});

var TAG_FLAG_PARENT = 1;
var TAG_FLAG = 11;
var UILayer = cc.Layer.extend({
	init:function(){
		this.setMouseEnabled(true);
		
		var parent = cc.Layer.create();
		parent.setPosition(MAP_OFFSET);
		this.addChild(parent, 0, TAG_FLAG_PARENT);
		this.flagParent = parent;
		
		var normst = cc.Sprite.create(R_QUIT_MENU, cc.rect(0,0,64,64));
		var selst = cc.Sprite.create(R_QUIT_MENU, cc.rect(0,64,64,64));
		var quit = cc.MenuItemSprite.create(normst,selst,this.quitPlay, this);
		var menu = cc.Menu.create(quit);
		menu.setPosition(cc.p(0,0));
		this.addChild(menu, 1);	
		quit.setPosition(cc.p(750,550));
	},
	
	quitPlay:function(){
		TW.sock.disconnect();
	},
	
	enableSetPos:function(L){
		TW.canSetPos = true;
		
		var thiz = this;
		this.scheduleOnce(function(){
			TW.canSetPos = false;
			var flag = thiz.flagParent.getChildByTag(TAG_FLAG);
			if(flag){
				flag.removeFromParent(true);
			}
		}, L);
	},
	
	onMouseUp:function(evt){
		if(TW.canSetPos){
			var pos = mouse2grid(evt.getLocation());
			if(pos){
				TW.sock.emit('pos', pos);
			}
		}
		
	},
});